using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Data;
using Microsoft.SharePoint;
using System.Xml;
using Starznet.SharePoint.Utilities.CAML;
using Starznet.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

namespace Starznet.SharePoint.SPDAT.ApplicationPages.Settings
{
    public class CAMLHelperPage : StarznetBaseLayoutPage
    {
        protected DataList dlLists;
        protected ListBox lbFields;
        protected DropDownList ddFilterType;
        protected Label lblFieldType;
        protected TextBox txtFilterValue;
        protected Literal litOutput;
        protected TextBox txtQueryXMLRaw;
        protected RadioButtonList rbBoolOpList;
        protected SPGridView GvResults;
        protected RadioButtonList rbSortOrder;
        protected InputFormControl inputTestRes;

        protected Button CmdAddWhere;
        protected Button CmdAddOrder;
        protected Button CmdTest;
        protected Button CmdClear;

        protected SPList _oList;
        protected CamlQuery _oQ;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            lbFields.SelectedIndexChanged += new EventHandler(lbFields_SelectedIndexChanged);

            if (!string.IsNullOrEmpty(this.txtQueryXMLRaw.Text))
                _oQ = new CamlQuery(this.txtQueryXMLRaw.Text);
            else
                _oQ = new CamlQuery("<Query />");

            if (Request.QueryString["ListId"] != null)
            {
                _oList = SPContext.Current.Web.Lists[new Guid(Request.QueryString["ListId"].ToString())];
                this.GetFields(_oList);
            }

            if (IsPostBack) return;

            DataTable oData = new DataTable();
            oData.Columns.Add("Title");
            oData.Columns.Add("ListID");
            oData.Columns.Add("ListImage");

            DataRow oRow = null;
            foreach (SPList oList in SPContext.Current.Web.Lists)
            {
                oRow = oData.NewRow();
                oRow["Title"] = oList.Title;
                oRow["ListID"] = oList.ID.ToString();
                oRow["ListImage"] = oList.ImageUrl;

                oData.Rows.Add(oRow);
            }

            this.dlLists.DataSource = oData;
            this.dlLists.DataBind();
        }

        void lbFields_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Determine the type of field
            SPField oField = _oList.Fields[new Guid(this.lbFields.SelectedValue.ToString())];
            this.lblFieldType.Text = "(" + oField.TypeAsString + ")"; this.lblFieldType.Visible = true;

            this.CmdAddWhere.Enabled = true;
            this.CmdAddOrder.Enabled = true;
        }

        protected void BtnUpdate_Click(object Sender, EventArgs e)
        { }

        protected void cmdAddWhere_Click(object Sender, EventArgs e)
        {
            SPField oField = _oList.Fields[new Guid(this.lbFields.SelectedValue)];
            _oQ.AddWhereField(oField, this.txtFilterValue.Text, this.ddFilterType.SelectedValue, this.rbBoolOpList.SelectedValue);
            this.WriteQueryXML();
        }

        protected void cmdAddOrder_Click(object Sender, EventArgs e)
        {
            SPField oField = _oList.Fields[new Guid(this.lbFields.SelectedValue)];
            _oQ.AddOrderByField(oField.InternalName, (this.rbSortOrder.SelectedValue=="Asc") ? CamlQuery.SortTypes.Ascending : CamlQuery.SortTypes.Descending);
            this.WriteQueryXML();
        }

        protected void cmdTest_Click(object Sender, EventArgs e)
        {
            SPQuery oQuery = new SPQuery();
            XmlNode oQueryNode = _oQ.CamlDocument.SelectSingleNode("//Query");
            oQuery.Query = oQueryNode.InnerXml;

            SPListItemCollection oItems = _oList.GetItems(oQuery);
            DataTable oDT = new DataTable();
            if (oItems.Count > 0)
            {
                foreach (SPField oField in oItems[0].Fields)
                {
                    if (oField.Type == SPFieldType.Text && !oField.InternalName.StartsWith("_"))
                    {
                        BoundField oCol = new BoundField();
                        oCol.HeaderText = oField.Title;
                        oCol.DataField = oField.InternalName;
                        this.GvResults.Columns.Add(oCol);

                        oDT.Columns.Add(oField.InternalName);
                    }
                }

                DataRow oRow = null;
                foreach (SPListItem oItem in oItems)
                {
                    oRow = oDT.NewRow();
                    foreach (SPField oField in oItem.Fields)
                    {
                        if (oField.Type == SPFieldType.Text && !oField.InternalName.StartsWith("_"))
                        {
                            if(oItem[oField.InternalName] != null)
                                oRow[oField.InternalName] = oItem[oField.InternalName].ToString();
                        }
                    }
                    oDT.Rows.Add(oRow);
                }

                this.GvResults.DataSource = oDT;
                this.GvResults.DataBind();

                this.inputTestRes.Visible = true;
            }
        }

        protected void cmdClear_Click(object Sender, EventArgs e)
        {
            _oQ.Clear();
            this.txtQueryXMLRaw.Text = String.Empty;
            this.litOutput.Text = String.Empty;
        }

        private void GetFields(SPList List)
        {
            //this.lbFields.Items.Clear();
            foreach (SPField oField in List.Fields)
            {
                if(this.lbFields.Items.FindByValue(oField.Id.ToString()) == null)
                    this.lbFields.Items.Add(new ListItem(oField.Title, oField.Id.ToString()));
            }
        }

        private void WriteQueryXML()
        {
            this.litOutput.Text = Utility.TransformXML(_oQ.CamlDocument.InnerXml);
            this.txtQueryXMLRaw.Text = _oQ.CamlDocument.InnerXml;
            this.CmdTest.Enabled = true;
            this.CmdClear.Enabled = true;
        }
    }
}